package com.team233.zuccecho.service.impl;

import com.alibaba.fastjson.JSON;
import com.team233.zuccecho.Bean.*;
import com.team233.zuccecho.dto.QuestionDto;
import com.team233.zuccecho.dto.QuestionnaireDto;
import com.team233.zuccecho.dto.TeacherDto;
import com.team233.zuccecho.exception.EchoServiceException;
import com.team233.zuccecho.repository.ClazzRepository;
import com.team233.zuccecho.repository.QuestionRepository;
import com.team233.zuccecho.repository.QuestionnaireRepository;
import com.team233.zuccecho.repository.TeacherRepository;

import com.team233.zuccecho.service.inter.TeacherInterface;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Set;


@Service
@CacheConfig(cacheNames = "teacher")
public class TeacherImpl implements TeacherInterface {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    TeacherRepository teacherRepository;
    @Autowired
    ClazzRepository clazzRepository;
    @Autowired
    QuestionRepository questionRepository;
    @Autowired
    QuestionnaireRepository questionnaireRepository;
    @Autowired
    private RestHighLevelClient client;

    @Override
    public String login(String tea_id, String tea_pwd) throws EchoServiceException {
        Teacher teacher=teacherRepository.findTeaById(tea_id);
        if(teacher==null) throw new EchoServiceException("该教师不存在"+tea_id);

        if(teacher.getTea_pwd().equals(tea_pwd)) return tea_id;
        return "";
    }

    @Override
    public Integer modifyPwd(String tea_id, String oldpwd, String newpwd) throws EchoServiceException {
        Teacher teacher=teacherRepository.findTeaById(tea_id);
        if(oldpwd.equals(teacher.getTea_pwd())) {
            teacherRepository.ModifyPwd(newpwd,tea_id);
            return 1;
        }
        throw new EchoServiceException("初始密码错误");
    }

    @Override
    public List<Teacher> addTea(List<TeacherDto> teaList) throws EchoServiceException {
        List<Teacher> teas=new ArrayList<>();
        for(TeacherDto tea:teaList){
            if(teacherRepository.findTeaById(tea.getTea_id())!=null)
                throw new EchoServiceException("该教师已存在" + tea.getTea_id());

            Teacher teacher=new Teacher();
            BeanUtils.copyProperties(tea,teacher);
            teas.add(teacher);
        }

        if(teaList.size()!=0){
            teacherRepository.saveAll(teas);
            return teas;
        }
        return null;
    }

    /**
     *教师发布问卷
     */
    @Override
    public Long releaseQn(QuestionnaireDto questionnaireDto) throws EchoServiceException, IOException {
        if(questionnaireDto.getQuestionnaireID() != null){
            throw new EchoServiceException("发布问卷不能有id");
        }
        if(questionnaireDto.getQuestionSet() != null){
            questionnaireDto.getQuestionSet().stream().forEach(
                    question -> {
                        if(question.getContent().equals("")){
                            throw new EchoServiceException(question.getQuestionID()+"问题内容不能为空");
                        }
                        if(question.getQuestionType() == 1 || question.getQuestionType() == 2){
                            if(question.getAnswerlist().equals("")){
                                throw new EchoServiceException(question.getQuestionID()+"选择题必须要有选项");
                            }
                        }
                        if(question.getQuestionType() == null){
                            throw new EchoServiceException(question.getQuestionID()+"问卷类型不能为空");
                        }
                    }
            );
        }
        Questionnaire questionnaire = new Questionnaire();
        questionnaire.setCreateTime(new Timestamp(Calendar.getInstance().getTimeInMillis()));
        questionnaire.setEndTime(Timestamp.valueOf(questionnaireDto.getEndTime()));

        Teacher teacher = teacherRepository.findTeaById(questionnaireDto.getTea_id());
        Clazz clazz = clazzRepository.findById(questionnaireDto.getClazz_id());
        questionnaire.setTeacher(teacher);
        questionnaire.setClazz(clazz);
        List<Question> Tquestions = questionRepository.getTemQs(questionnaireDto.getTemplate_id());
        List<Question> questions = new ArrayList<>();
        for(QuestionDto questionDto:questionnaireDto.getQuestionSet()){
            Question question = new Question();
            question.setQuestionType(questionDto.getQuestionType());
            question.setContent(questionDto.getContent());
            question.setAnswerList(questionDto.getAnswerlist());
            questionRepository.save(question);
            questions.add(question);
        }
        Tquestions.addAll(questions);
        questionnaire.setQuestionSet(Tquestions);
        questionnaireRepository.save(questionnaire);

        QnEntity qnEntity=new QnEntity();
        qnEntity.setCreateTime(new Timestamp(Calendar.getInstance().getTimeInMillis()));
        qnEntity.setEndTime(Timestamp.valueOf(questionnaireDto.getEndTime()));
        qnEntity.setClazz_id(questionnaireDto.getClazz_id());
        qnEntity.setTea_id(questionnaireDto.getTea_id());
        qnEntity.setQuesList(questionnaireDto.getQuestionSet().toString());
        qnEntity.setTemplate_id(questionnaireDto.getTemplate_id());
        qnEntity.setQn_id(questionnaire.getQuestionnaireID());

        //先判断索引是否存在
        GetIndexRequest rq = new GetIndexRequest("questionnaire");
        boolean exists = client.indices().exists(rq, RequestOptions.DEFAULT);
        //如果索引不存在，则创建索引
        if(!exists){
            CreateIndexRequest request = new CreateIndexRequest("questionnaire");
            CreateIndexResponse createIndexResponse =
                    client.indices().create(request, RequestOptions.DEFAULT);
            System.out.println(createIndexResponse);
        }

        IndexRequest req=new IndexRequest("questionnaire");
        req.id(""+questionnaire.getQuestionnaireID());
        req.source(JSON.toJSONString(qnEntity), XContentType.JSON);
        IndexResponse indexResponse = client.index(req, RequestOptions.DEFAULT);

        System.out.println(indexResponse.toString());//数据
        System.out.println(indexResponse.status());
        /**
         * 蔡海龙 4/24/2022
         */
        //测试 清空缓存
//        Set<String> keys = redisTemplate.keys("*");
//        redisTemplate.delete(keys);
        //教师发布问卷时在allNumber中填入问卷对应班级的总人数,此时的otherNumber未填写人数与应填写人数相同
//        List<Long> stuIds=new ArrayList<Long>();
//        if(clazz.getStudentlist()!=null&&clazz.getStudentlist().size()!=0){
//            for (Student stu: clazz.getStudentlist()) {
//                stuIds.add(stu.getStu_id());
//            }
//        }

        Long qn_id=questionnaire.getQuestionnaireID();
//        redisTemplate.opsForList().rightPushAll("questionnaire-"+qn_id+":allNumber", stuIds);
//        redisTemplate.opsForList().rightPushAll("questionnaire-"+qn_id+":otherNumber", stuIds);
//        System.out.println(redisTemplate.opsForList().range("questionnaire-"+qn_id+":allNumber",
//                0,-1));

        return qn_id;
    }

    @Override
    public List<Questionnaire> QueryTeaQuestionnaire(String tea_id) throws EchoServiceException {
        List<Questionnaire> teaQnInfo = new ArrayList<>();
        List<Questionnaire> questionnaires = questionnaireRepository.getTeaALlQn(Long.parseLong(tea_id));
        if(questionnaires == null){
            throw new EchoServiceException("该教师还未添加问卷信息");
        }else{
            for (Questionnaire q: questionnaires){
                teaQnInfo.add(q);
            }
        }
        return teaQnInfo;
    }

    public List<Feedback> QueryFeedback(Long qn_id) throws EchoServiceException{
        Questionnaire questionnaire=questionnaireRepository.findQNById(qn_id);
        if(questionnaire==null) throw new EchoServiceException("该问卷不存在");
        return questionnaire.getFeedbackList();
    }

    @Override
    public List<Clazz> QueryTeaClazz(String tea_id) throws EchoServiceException {
        Teacher teacher=teacherRepository.findTeaById(tea_id);
        if(teacher==null) throw new EchoServiceException("该教师不存在");
        return clazzRepository.findByTeaId(tea_id);
    }
}
